<template>
  <transition name="el-zoom-in-center">
    <div
      class="el-popper is-pure is-light el-dropdown__popper"
      v-show="state.show"
      aria-hidden="false"
      data-popper-placement="bottom"
      :key="Math.random()"
      :style="{
        left: state.axis.x - 14 + 'px',
        top: state.axis.y + 5 + 'px'
      }"
    >
      <ul class="el-dropdown-menu">
        <template v-for="item in data" :key="item.label">
          <li
            class="el-dropdown-menu__item"
            :class="item.disabled ? 'is-disabled' : ''"
            tabindex="-1"
            aria-hidden="false"
            @click="onContextmenuItem(item)"
          >
            {{ item.label }}
          </li>
        </template>
      </ul>

      <span
        class="el-popper__arrow"
        :style="{ left: `${state.arrowX}px` }"
      ></span>
    </div>
  </transition>
</template>

<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import { useEventListener } from '@vueuse/core'
import type { IContextmenuItem, IAxis } from '../type'

// 不能使用导出的 interface vue的issue已存在，尚未解决
export interface IContextmenuProps {
  data: IContextmenuItem[]
}

withDefaults(defineProps<IContextmenuProps>(), {
  data: () => []
})

const emits = defineEmits(['contextmenuItemEmit'])

const state = reactive({
  axis: {
    x: 0,
    y: 0
  },
  show: false,
  arrowX: 10,
  menu: null //右键传下来的对应的menu数据
})

const onShowContextmenu = (menu: any, axis: IAxis) => {
  state.axis = axis
  state.show = true
  state.menu = menu
}
//为啥用这个方法而不是通过发送时间父组件来修改,因为是页面多个地方需要来关闭此组件
const onCloseContextmenu = () => {
  state.show = false
}

const onContextmenuItem = (item: IContextmenuItem) => {
  if (item.disabled) return
  item.menu = state.menu
  emits('contextmenuItemEmit', item)
}
onMounted(() => {
  useEventListener(document, 'click', onCloseContextmenu)
})
defineExpose({ onShowContextmenu, onCloseContextmenu })
</script>

<style lang="less" scoped>
.contextmenu {
  z-index: 999;
}
.el-dropdown-menu__item:not(.is-disabled) {
  &:hover {
    background-color: var(--el-dropdown-menuItem-hover-fill);
    color: var(--el-dropdown-menuItem-hover-color);
  }
}
</style>
